// 购物车模块
const state = {
    items: [], // 购物车内部商品列表
    checkAll: false // 全选状态
}

const getters = {
    // 计算总价
    totalPrice: (state) => {
        return state.items
            .filter(item => item.check)
            .reduce((total, item) => total + parseFloat(item.price) * parseInt(item.count), 0);
    },
    
    // 统计选中的商品总数量
    checkNumber: (state) => {
        return state.items
            .filter(item => item.check)
            .reduce((total, item) => total + parseInt(item.count), 0);
    },
    
    // 判断是否所有商品都被选中
    allChecked: (state) => {
        return state.items.every(item => item.check);
    }
}

const actions = {
    insert(context, item) {
        context.commit('insert', item)
    },
    del(context, id) {
        context.commit('del', id)
    },
    updateCount(context, { id, count }) {
        context.commit('UPDATE_COUNT', { id, count })
    },
    toggleCheck(context, id) {
        context.commit('TOGGLE_CHECK', id)
    },
    toggleAll(context, checked) {
        context.commit('TOGGLE_ALL', checked)
    }
}

const mutations = {
    // 添加商品到购物车
    insert(state, item) {
        const existingItem = state.items.find(v => v.id === item.id)
        if (existingItem) {
            existingItem.count++
        } else {
            state.items.push({
                ...item,
                count: 1,
                check: true // 新添加的商品默认选中
            })
        }
    },
    
    // 删除商品
    del(state, id) {
        state.items = state.items.filter(item => item.id !== id);
    },
    
    // 更新商品数量
    UPDATE_COUNT(state, { id, count }) {
        const item = state.items.find(item => item.id === id);
        if (item) {
            item.count = count;
        }
    },
    
    // 切换单个商品选中状态
    TOGGLE_CHECK(state, id) {
        const itemIndex = state.items.findIndex(item => item.id === id);
        if (itemIndex !== -1) {
            // 创建新对象确保响应式更新
            state.items[itemIndex] = {
                ...state.items[itemIndex],
                check: !state.items[itemIndex].check
            };
            
            // 更新全选状态
            state.checkAll = state.items.every(item => item.check);
        }
    },
    
    // 全选/取消全选
    TOGGLE_ALL(state, checked) {
        // 创建新数组确保响应式更新
        state.items = state.items.map(item => ({
            ...item,
            check: checked
        }));
        
        state.checkAll = checked;
    }
}

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}